import {ActionType, ProCard, ProColumns} from '@ant-design/pro-components';
import {
  PageContainer,
  ProTable,
  StatisticCard,
} from '@ant-design/pro-components';
import React, {useRef, useState} from 'react';
import {getReportDetailStressPage} from './service';
import {useRequest, useSearchParams} from '@umijs/max';
import CustomCode from '@/components/CustomCode';
import {getReport} from './service'
import CustomPie from './components/CustomPie'
import SummaryChart from "./components/SummaryChart";
import dayjs from "dayjs";

const {Statistic, Divider} = StatisticCard;

const TableList: React.FC = () => {
  const [searchParams] = useSearchParams()
  const reportId = searchParams.get("reportId")
  const actionRef = useRef<ActionType>();
  const [summary, setSummary] = useState({
    averageResponseTime: 0,
    QPS: 0,
    maximumResponseTime: 0,
    errorRequestPercentage: 0,
    minimumResponseTime: 0
  })

  const {data, loading} = useRequest(() => {
    return getReport({id: reportId})
  }, {
    onSuccess(data) {
      const summaryData = JSON.parse(data?.summary)
      setSummary({
        averageResponseTime: summaryData['平均响应时间(毫秒)'],
        QPS: summaryData['QPS'],
        maximumResponseTime: summaryData['最大响应时间(毫秒)'],
        errorRequestPercentage: summaryData['错误请求百分比'],
        minimumResponseTime: summaryData['最小响应时间(毫秒)']
      })
    }
  })

  const columns: ProColumns<any>[] = [
    {
      title: 'ID',
      valueType: 'indexBorder',
      fixed: 'left',
      width: 80,
    },
    {
      title: '报告ID',
      dataIndex: 'reportId',
    },
    {
      title: '响应码',
      dataIndex: 'responseCode',
    },
    {
      title: '响应数据',
      dataIndex: 'responseData',
      render(dom,) {
        return <CustomCode width={340} height={120} value={dom}/>
      },
    },
    {
      title: '响应头',
      dataIndex: 'responseHeader',
      render(dom,) {
        return <CustomCode width={340} height={120} value={dom}/>
      },
    },
    {
      title: '断言信息',
      dataIndex: 'assertInfo',
      render(dom,) {
        return <CustomCode width={340} height={120} value={dom}/>
      },
    },
    {
      title: '错误数量',
      dataIndex: 'errorCount',
    },
    {
      title: '错误百分比',
      dataIndex: 'errorPercentage',
    },
    {
      title: '最大时间',
      dataIndex: 'maxTime',
    },
    {
      title: '平均时间',
      dataIndex: 'meanTime',
    },
    {
      title: '最小时间',
      dataIndex: 'minTime',
    },
    {
      title: '接收KB/秒',
      dataIndex: 'receiveKBPerSecond',
    },
    {
      title: '发送KB/秒',
      dataIndex: 'sentKBPerSecond',
    },
    {
      title: '请求位置',
      dataIndex: 'requestLocation',
    },
    {
      title: '请求头',
      dataIndex: 'requestHeader',
      render(dom,) {
        return <CustomCode width={340} height={120} value={dom}/>
      },
    },
    {
      title: '请求体',
      dataIndex: 'requestBody',
      render(dom,) {
        return <CustomCode width={340} height={120} value={dom}/>
      },
    },
    {
      title: '请求率',
      dataIndex: 'requestRate',
    },

    {
      title: '采样器数量',
      dataIndex: 'samplerCount',
    },
    {
      title: '采样器标签',
      dataIndex: 'samplerLabel',
    },
    {
      title: '线程数量',
      dataIndex: 'threadCount',
    },
    {
      title: '采样时间',
      dataIndex: 'sampleTime',
      valueType: 'dateTime'
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
      valueType: 'dateTime'
    },
    {
      title: '修改时间',
      dataIndex: 'gmtModified',
      valueType: 'dateTime'
    },
  ];

  const valueEnum = {
    EXECUTE_SUCCESS: {text: '执行成功', status: 'success'},
    EXECUTING: {text: '执行中', status: 'processing'},
    COUNTING_REPORT: {text: '统计报告', status: 'processing'},
    EXECUTE_FAIL: {text: '执行失败', status: 'error'},
  }
  // {"平均响应时间(毫秒)":1.61,"QPS":109.17,"最大响应时间(毫秒)":18,"错误请求百分比":0.0,"最小响应时间(毫秒)":0}

  return (
    <PageContainer>
      <StatisticCard.Group
        style={{marginBottom: 24}}
        loading={loading}
        direction={'row'}>
        <StatisticCard
          statistic={{
            title: '执行总数',
            value: data?.quantity,
            status: valueEnum[data?.executeState]?.status,
            tip: valueEnum[data?.executeState]?.text,
          }}
        />
        <Divider type={'vertical'}/>
        <StatisticCard
          statistic={{
            title: '成功数量',
            value: data?.passQuantity,
            description: <Statistic title="占比"
                                    value={Number(data?.passQuantity / data?.quantity * 100).toFixed(2) + '%'}/>,
          }}
          chart={
            <CustomPie type="success" quantity={data?.quantity} current={data?.passQuantity}/>
          }
          chartPlacement="left"
        />
        <StatisticCard
          statistic={{
            title: '失败数量',
            value: data?.failQuantity,
            description: <Statistic title="占比"
                                    value={Number(data?.failQuantity / data?.quantity * 100).toFixed(2) + '%'}/>,
          }}
          chart={
            <CustomPie type="error" quantity={data?.quantity} current={data?.failQuantity}/>
          }
          chartPlacement="left"
        />
      </StatisticCard.Group>

      <ProCard
        title="摘要"
        extra={dayjs(data?.startTime).format('YYYY年MM月DD日HH时mm分ss秒')+'-'+dayjs(data?.endTime).format('YYYY年MM月DD日HH时mm分ss秒')}
        split={'vertical'}
        headerBordered
        style={{marginBottom: 24}}
      >
        <ProCard split="horizontal">
          <ProCard split="vertical">
            <StatisticCard
              statistic={{
                title: '平均响应时间',
                value: summary?.averageResponseTime,
                suffix: '毫秒',
                // description: (
                //   <Statistic
                //     title="较本月平均流量"
                //     value="8.04%"
                //     trend="down"
                //   />
                // ),
              }}
            />
            <StatisticCard
              statistic={{
                title: '最小响应时间',
                value: summary?.minimumResponseTime,
                suffix: '毫秒',
              }}
            />
          </ProCard>
          <ProCard split="vertical">
            <StatisticCard
              statistic={{
                title: '最大响应时间',
                value: summary?.maximumResponseTime,
                suffix: '毫秒',
              }}
            />
            <StatisticCard
              statistic={{
                title: '错误请求百分比',
                value: summary?.errorRequestPercentage,
                suffix: '%',
              }}
            />
          </ProCard>
          <ProCard split="vertical">
            <StatisticCard
              statistic={{
                title: 'QPS',
                value: summary?.QPS,
                suffix: '%',
                // description: (
                //   <Statistic title="月同比" value="8.04%" trend="up" />
                // ),
              }}
            />
            <StatisticCard
              statistic={{
                title: '执行耗时',
                value: data?.expandTime,
                suffix: '毫秒',
                // description: (
                //   <Statistic title="月同比" value="8.04%" trend="up" />
                // ),
              }}
            />
          </ProCard>
        </ProCard>
        <ProCard split={'horizontal'}>
          <ProCard split="vertical">
            <StatisticCard
              chart={<SummaryChart data={[
                {type: '平均响应时间', value: summary?.averageResponseTime},
                {type: '最小响应时间', value: summary?.minimumResponseTime},
                {type: '最大响应时间', value: summary?.maximumResponseTime},
                {type: '错误请求百分比', value: summary?.errorRequestPercentage},
                {type: 'QPS', value: summary?.QPS},
              ]}/>}
            />
          </ProCard>
        </ProCard>

      </ProCard>

      <ProTable<any>
        actionRef={actionRef}
        rowKey="id"
        search={false}
        toolBarRender={false}
        scroll={{x: 'max-content'}}
        request={async ({pageSize, current, ...params}) => {
          // @ts-ignore
          const res = await getReportDetailStressPage({
            current,
            pageSize,
            ...params,
            reportId,
            type: 'STRESS'
          })
          const total = res?.data?.totalRecords || 0
          // @ts-ignore
          const data = res?.data?.currentData || []
          return {
            data,
            total,
          }
        }}
        columns={columns}
      />
    </PageContainer>
  );
};

export default TableList;
